package m2_work;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");

        Channel c = f.newConnection().createChannel();
        //定义队列
        c.queueDeclare(
                "task_queue",
                true, //是否是持久队列
                false,//排他队列、独占队列 true--只能有一个消费者独占
                false,//自动删除
                null);//其他属性

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到："+msg);

                for (int i = 0; i < msg.length(); i++) {
                    if (msg.charAt(i) == '.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                System.out.println("消息处理结束");
                //向服务器发送回执
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        c.basicQos(1);  //先配置手动ack 再设置Qos 实现消息合理分配

        //接收数据、消费数据
        c.basicConsume(
                "task_queue",
                false,  //ack回执，true--自动ack
                deliverCallback,
                cancelCallback);
    }
}
